#pragma once
//套接字的封装
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include<arpa/inet.h>
#include<string>
#include<cstring>
#include<cstdlib>
const int backlog=5;
class Sock
{
    public:
    Sock()
    {

    }
    ~Sock()
    {
    }
    void Socket()
    {
        //1.套接字的创建
       listen_fd= socket(AF_INET,SOCK_STREAM,0);
      if(listen_fd<0)
      {
        exit(1);
      }
    }
    void Bind(const uint16_t&port)
    {
        //2.准备数据
        
       struct sockaddr_in local;
       memset(&local,0,sizeof(local));
       local.sin_family=AF_INET;
       local.sin_port=htons(port);
       local.sin_addr.s_addr=INADDR_ANY;
       //3.绑定
        if(bind(listen_fd,(sockaddr*)&local,sizeof(local))<0)
        {
            exit(2);
        }
    }
    void Listen()
    {
        //监听
      int n=  listen(listen_fd,backlog);
      if(n<0)
      {
        exit(3);
      }
    }
    int Accept(std::string *ip,uint16_t*port)
    {
        //同时获取对方信息
        struct sockaddr_in peer;
        socklen_t peerlen=sizeof(peer);
        //获取新链接
       int newfd= accept(listen_fd,(sockaddr*)&peer,&peerlen);
        if(newfd<0){return -1;}
        *port= ntohs(peer.sin_port);
        char buffer[64];
        inet_ntop(AF_INET,&peer.sin_addr,buffer,sizeof(peer));
        *ip=buffer;
       return newfd;
    }

    bool Connet(const uint16_t&port,const std::string&ip)
    {
        struct sockaddr_in client;
        memset(&client,0,sizeof(client));
        client.sin_family=AF_INET;
        client.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&client.sin_addr);
        int n=connect(listen_fd,(sockaddr*)&client,sizeof(client));
        if(n<0)
        {
            return false;
        }
        return true;
    }
    int Fd()
    {
        return listen_fd;
    }
    void Close()
    {
        close(listen_fd);
    }
    private:
    int listen_fd;//监听套接字

};